package zdh.jfinabbsapp.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.kymjs.kjframe.http.HttpCallBack;

import java.util.ArrayList;
import java.util.List;

import zdh.jfinabbsapp.R;
import zdh.jfinabbsapp.activity.TopicActivity;
import zdh.jfinabbsapp.api.API;
import zdh.jfinabbsapp.api.dao.GeneralTopic;
import zdh.jfinabbsapp.util.Session;

/**
 * 作者：zdh1000
 * 创建时间： 2015/6/29 19:58
 * 邮箱：wdzdh1000@163.com
 */
public class GeneralTopicListFragment extends ListFragment implements AbsListView.OnScrollListener {
    private View footerview;
    private String tab = "gs";
    private List<GeneralTopic> topicList;
    private Context context;
    private NewAdapter adapter;
    private String tag;
    private int page = 1;
    private int loading = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i(tag, "->handler->handleMessage");
            if (page == 1) {
//                initListView();
                adapter.notifyDataSetChanged();
            } else {
                Log.d("GTF", "adapter.notifyDataSetChanged()");
                adapter.notifyDataSetChanged();
            }
//            footerview.setVisibility(View.GONE);
            page++;

        }
    };


    public GeneralTopicListFragment() {
        topicList = new ArrayList<>();
    }

    public static GeneralTopicListFragment instance(Bundle bundle) {
        GeneralTopicListFragment fragment = new GeneralTopicListFragment();
        fragment.tab = bundle.getString("tab");
        return fragment;
    }

    @Override
    public void onCreate(Bundle bundle) {
        Log.i(tag, "->onCreate");
        super.onCreate(bundle);
        context = getActivity();

        new NThread().start();
//        headerView = new TextView(context);
//        ((TextView)headerView).setText("上拉加载更多");
//        getListView().addHeaderView(headerView);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListView();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    private void initListView() {
        Log.i(tag, "->initListView");
        footerview = getActivity().getLayoutInflater().inflate(R.layout.list_cell_footer,null);
        getListView().addFooterView(footerview);
        footerview.setVisibility(View.VISIBLE);
        adapter = new NewAdapter(context, R.layout.item_generaltopic, topicList);
        setListAdapter(adapter);
        getListView().setOnScrollListener(this);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent intent = new Intent(context, TopicActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("id", topicList.get(position).getId());
        intent.putExtras(bundle);

        startActivity(intent);

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (loading == 0 && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            Log.d("GTF latItem", String.valueOf(getListView().getLastVisiblePosition()));
            if (getListView().getLastVisiblePosition() == topicList.size()) {
//                Toast.makeText(context,"上拉加载更多",Toast.LENGTH_LONG).show();
//                footerview.setVisibility(View.VISIBLE);
                new NThread().start();
            }
        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//        new NThread().start();
    }

    private class NThread extends Thread {
        @Override
        public void run() {
            List<GeneralTopic> list = new ArrayList<>();
            String url = API.getTopicListUrl(tab, page);
            Log.i("NThread", "url:" + url);
            loading = 1;
            if (Session.isAutoUpdate()) {
                Log.d("NThread", "自动更新，从网络获取数据.");
                //线程获取栏目，并初始化leftItem
                API.http.get(url, new HttpCallBack() {
                    public void onSuccess(String t) {
                        super.onSuccess(t);
                        topicList.addAll(API.getTopicListByJson(t));
                        loading = 0;
                        handler.sendEmptyMessage(0);
                    }
                });
            }else{
                Log.d("NThread", "从本地获取数据.");
                String temp = new String(API.http.getCache(url));
                list = API.getTopicListByJson(temp);
                if(list.size()==0||list == null)
                {
                    Log.d("NThread", "从网络获取数据.");
                    //线程获取栏目，并初始化leftItem
                    API.http.get(url, new HttpCallBack() {
                        public void onSuccess(String t) {
                            super.onSuccess(t);
                            topicList.addAll(API.getTopicListByJson(t));
                            loading = 0;
                            handler.sendEmptyMessage(0);
                        }
                    });
                }
                handler.sendEmptyMessage(0);
                loading = 0;
            }
        }
    }

    class NewAdapter extends ArrayAdapter<GeneralTopic> {
        private String tag;

        public NewAdapter(Context context, int resource, List<GeneralTopic> objects) {
            super(context, resource, objects);
            Log.i(tag, "->NewAdapter->init");
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.i(tag, "->NewAdapter->getView");
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();

                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_generaltopic, null);
                holder.imageView = (ImageView) convertView
                        .findViewById(R.id.imageView);
                holder.textView_title = (TextView) convertView
                        .findViewById(R.id.textView_title);
                holder.textView_tab = (TextView) convertView
                        .findViewById(R.id.textView_tab);
                holder.textView_author = (TextView) convertView
                        .findViewById(R.id.textView_author);
                holder.textView_time = (TextView) convertView
                        .findViewById(R.id.textView_time);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            GeneralTopic temp = getItem(position);
            holder.textView_title.setText(temp.getTitle());
            if (temp.getTop() == 1) {
                holder.textView_tab.setBackgroundColor(getResources().getColor(R.color.background_green));
                holder.textView_tab.setText("置顶");
            } else {
                holder.textView_tab.setBackgroundColor(getResources().getColor(R.color.background_grad));
                holder.textView_tab.setText(temp.getSectionName());
            }

            holder.textView_author.setText(temp.getNickName());
            holder.textView_time.setText(temp.getInTime());

            return convertView;
        }

        public final class ViewHolder {
            public ImageView imageView;
            public TextView textView_title;
            public TextView textView_tab;
            public TextView textView_author;
            public TextView textView_time;
        }

    }
}
